#!/bin/bash
set -e

extract_latest_version_tgz() {
    # Takes in a path to a chart's directory, finds the latest version's tgz and extracts it
    # All crd tgz are ignored
    # Max depth is set to prevent extracting a tgz contained within another tgz, which is the case for charts containing a helm repo
    LATEST_VERSION_TGZ_PATH=$(find $1 -maxdepth 1 -name "*.tgz" ! -name "*crd*.tgz" -print | sort -Vr | head -1)
    if [[ $LATEST_VERSION_TGZ_PATH ]]; then
        tar -xvf $LATEST_VERSION_TGZ_PATH -C $(dirname $LATEST_VERSION_TGZ_PATH)
    fi
}
export -f extract_latest_version_tgz

./k3s-images.sh

source $(dirname $0)/version

ARCH=${ARCH:-"amd64"}
SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH:-"dev-v2.4"}
CHART_DEFAULT_BRANCH=${CHART_DEFAULT_BRANCH:-"dev-v2.5"}

cd $(dirname $0)/../package

cp ../bin/rancher.yaml ../bin/rancher ../bin/agent ../bin/data.json ../bin/k3s-airgap-images.tar .

IMAGE=${REPO}/rancher:${TAG}
AGENT_IMAGE=${REPO}/rancher-agent:${AGENT_TAG}
RUNTIME_IMAGE=${REPO}/rancher-runtime:${TAG}

if [ ${ARCH} == arm64 ]; then
    sed -i -e '$a\' -e 'ENV ETCD_UNSUPPORTED_ARCH=arm64' Dockerfile
fi

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg IMAGE_REPO=${REPO} --build-arg SYSTEM_CHART_DEFAULT_BRANCH=${SYSTEM_CHART_DEFAULT_BRANCH} --build-arg CHART_DEFAULT_BRANCH=${CHART_DEFAULT_BRANCH} -t ${IMAGE} .

docker build --build-arg VERSION=${TAG} --build-arg ARCH=${ARCH} --build-arg RANCHER_TAG=${TAG} --build-arg RANCHER_REPO=${REPO} -t ${AGENT_IMAGE} -f Dockerfile.agent .
if [ "${ARCH}" == amd64 ]; then
    docker build -t ${RUNTIME_IMAGE} -f Dockerfile.runtime .
fi

mkdir -p ../dist
echo ${IMAGE} > ../dist/images
echo ${AGENT_IMAGE} >> ../dist/images
echo Built ${IMAGE} #${AGENT_IMAGE}
echo

cd ../bin

if [ ! -d build/system-charts ]; then
    mkdir -p build
    git clone --branch $SYSTEM_CHART_DEFAULT_BRANCH https://github.com/rancher/system-charts build/system-charts
fi

if [ ! -d build/charts ]; then
    git clone --branch $CHART_DEFAULT_BRANCH https://github.com/rancher/charts build/charts

    # Iterate through chart directories and execute callback to extract latest version tgz
    find build/charts/assets -type d -maxdepth 1 -exec bash -c 'extract_latest_version_tgz {}' \;

    # Remove index to force building a virtual index like system charts
    rm -f build/charts/index.yaml build/charts/assets/index.yaml
fi

TAG=$TAG REPO=${REPO} go run ../pkg/image/export/main.go build/system-charts build/charts $IMAGE $AGENT_IMAGE

if [ ${ARCH} == amd64 ]; then
    # rancherd tarball
    rm -rf build/rancherd/bundle
    mkdir -p build/rancherd/bundle
    tar c -C ../cmd/rancherd/bundle . | tar x -C build/rancherd/bundle
    cp -vf rancherd build/rancherd/bundle/bin
    tar czf rancherd-${ARCH}.tar.gz -C build/rancherd/bundle .
fi
